package com.example.chasshelper.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.chasshelper.db.AppSQLiteHelper;
import com.example.chasshelper.model.Classroom;
import com.example.chasshelper.model.Course;
import com.example.chasshelper.model.Student;
import com.example.chasshelper.model.Teacher;
import com.example.chasshelper.utils.OkHttpUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class StudentDao  {
    private OkHttpClient okHttpClient = OkHttpUtils.getClient();
    private String ipUrl = OkHttpUtils.getUrl();
    private String url;
    /*
     * 查询所有
     * */
    public List<Student> findAll() {
        url = ipUrl + "/student/findAll";
        System.out.println("url:"+url);
        List<Student> list = new ArrayList<>();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string =response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //传过来的是list，需要用泛型来接收
            Type type = new TypeToken<List<Student>>() {}.getType();
            list = gson.fromJson(string, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /*
     * 根据id查询
     * */
    public  Student findById(Integer id) {
        url = ipUrl + "/student/findById?studentId=" + id;
        System.out.println("url:"+url);
        Student student=new Student();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            String string =response.body().string();
            //开始解析服务器传过来的json数据
            Gson gson = new Gson();
            //接收数据
            student = gson.fromJson(string, Student.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return student;
    }

    /*
     * 修改密码
     * */
    public  void changePassword(Student student) {
        url = ipUrl + "/student/update?studentPassword=" + student.getStudentPassword()+"&studentId="+student.getStudentId();
        System.out.println("url:"+url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }

    /*
     * 修改手机号
     * */
    public  void changePhone(Student student) {
        url = ipUrl + "/student/update?studentPhone=" + student.getStudentPhone()+"&studentId="+student.getStudentId();
        System.out.println("url:"+url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }

    /*
     * 判断手机号是否已存在
     * */
    public  String existsByStudentPhone(String phone) {
        url = ipUrl + "/student/existsByStudentPhone?phone=" + phone;
        System.out.println("url:"+url);
        String result="";
        OkHttpClient okHttpClient = OkHttpUtils.getClient();
        Request request = new Request.Builder().url(url).get().build();
        try {
            //执行同步get请求
            Response response = okHttpClient.newCall(request).execute();
            //获得返回的字符串
            result =response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;
    }

    /*
     * 为学生添加课程
     * */
    public  void addCourse(Student student, Course course) {
        url = ipUrl + "/student/update?studentId="+student.getStudentId()+"&courseId="+course.getCourseId();
        System.out.println("url:"+url);
        Request request = new Request.Builder().url(url).get().build();
        final Map<String, Object> resultMap = new HashMap<>();
        //执行异步get请求
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.out.println("失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                System.out.println("成功");
            }
        });
    }
















    /*********************************************************************************************************************/
/*
    private String tableName = "student";
    private AppSQLiteHelper appSQLiteHelper;

    public StudentDao(Context context) {
        appSQLiteHelper = new AppSQLiteHelper(context);

    }

    */
/*
     * 添加
     * *//*

    public boolean insert(Student student) {
        SQLiteDatabase sqLiteDatabase = appSQLiteHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("s_account",student.getS_account());
        contentValues.put("s_phone",student.getS_phone());
        contentValues.put("s_password",student.getS_password());
        long insert = sqLiteDatabase.insert(tableName, null, contentValues);
        System.out.println("StudentDao.insert()):"+insert);
        sqLiteDatabase.close();
        return insert > 0;
    }
    */
/*
     * 删除
     * *//*

    public boolean delete(Integer s_id) {
        SQLiteDatabase sqLiteDatabase = appSQLiteHelper.getWritableDatabase();
        long delete = sqLiteDatabase.delete(tableName, "s_id=", new String[]{s_id + ""});
        System.out.println("StudentDao.delete()):"+delete);
        sqLiteDatabase.close();
        return delete > 0;
    }
    */
/*
     * 修改
     * 唯一标识必须命名为id
     * *//*

    public boolean update(Student student, Integer s_id) {
        SQLiteDatabase sqLiteDatabase = appSQLiteHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("s_account",student.getS_account());
        contentValues.put("s_phone",student.getS_phone());
        contentValues.put("s_password",student.getS_password());
        long update = sqLiteDatabase.update(tableName, contentValues, "s_id=?", new String[]{String.valueOf(s_id)});
        System.out.println("StudentDao.update()):"+update);
        sqLiteDatabase.close();
        return update > 0;
    }
    */
/*
     * 无条件查询
     * *//*

    public List<Student> queryAll() {
        SQLiteDatabase sqLiteDatabase = appSQLiteHelper.getReadableDatabase();
        List<Student>list = null;
        Student student;
        Cursor cursor = sqLiteDatabase.query(tableName, null, null, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            list = new ArrayList<>();
            while (cursor.moveToNext()) {
                student = new Student();
                student.setS_id(Integer.valueOf(cursor.getString(cursor.getColumnIndex("s_id"))));
                student.setS_account(cursor.getString(cursor.getColumnIndex("s_account")));
                student.setS_phone(cursor.getString(cursor.getColumnIndex("s_phone")));
                student.setS_password(cursor.getString(cursor.getColumnIndex("s_password")));
                list.add(student);
            }
        }
        System.out.println("StudentDao.queryAll())!");
        sqLiteDatabase.close();
        return list;
    }

    */
/*
     * 根据id查询
     * *//*

    public Student queryOneById(Integer id) {
        SQLiteDatabase sqLiteDatabase = appSQLiteHelper.getReadableDatabase();
        Student student=new Student();
        Cursor cursor = sqLiteDatabase.query(tableName, null, "s_id=?", new String[]{String.valueOf(id)}, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToNext();
                student.setS_id(Integer.valueOf(cursor.getString(cursor.getColumnIndex("s_id"))));
                student.setS_account(cursor.getString(cursor.getColumnIndex("s_account")));
                student.setS_phone(cursor.getString(cursor.getColumnIndex("s_phone")));
                student.setS_password(cursor.getString(cursor.getColumnIndex("s_password")));
        }
        System.out.println("StudentDao.queryOneById())!");
        sqLiteDatabase.close();
        return student;
    }
*/
}
